package com.ruoyi.factory.util;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.ruoyi.system.service.SysOutputLogService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @ClassName WordUtil2
 * @Description: TODO
 * @Author LiuJiaji
 * @Date 2024/4/22 15:25
 **/
public class WordUtil2 {
    @Autowired
    private SysOutputLogService sysOutputLogServiceImpl;

    /**
 * EasyPoi 替换数据 导出 word
 * @param templatePath word模板地址
 * @param tempDir      临时文件存放地址
 * @param filename     文件名称
 * @param data         替换参数
 */
public static String easyPoiExport(HttpServletResponse response, String templatePath, String tempDir, String filename, List<Map<String, Object>> list) {
    Assert.notNull(templatePath, "模板路径不能为空");
    Assert.notNull(tempDir, "临时文件路径不能为空");
    Assert.notNull(filename, "文件名称不能为空");
    Assert.isTrue(filename.endsWith(".docx"), "文件名称仅支持docx格式");

    if (!tempDir.endsWith("/")) {
        tempDir = tempDir + File.separator;
    }

    File file = new File(tempDir);
    if (!file.exists()) {
        file.mkdirs();
    }

    try {
//            String userAgent = request.getHeader("user-agent").toLowerCase();
//            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
//                filename = URLEncoder.encode(filename, "UTF-8");
//            } else {
//                filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
//            }

        XWPFDocument document = WordExportUtil.exportWord07(templatePath, list);
        String tempPath = tempDir + filename;
        FileOutputStream out = new FileOutputStream(tempPath);
        document.write(out);
        //关闭线程占用
        document.close();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        String filenames = tempDir + filename;
        down(response,filenames);
        deleteTempFile(tempDir, filename);
    }
    return filename;
}

    public static void down(HttpServletResponse response, String pathstr) {
        try {
        // 获取服务器文件
        File file = new File(pathstr);
        InputStream ins = new FileInputStream(file);
        /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
        response.setContentType("multipart/form-data");
        /* 设置文件头：最后一个参数是设置下载文件名 */
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            os.close();
            ins.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }



    /**
     * 删除临时生成的文件
     */
    public static void deleteTempFile(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File f = new File(filePath);
        file.delete();
        f.delete();
    }
}
